<template>
  <div class="fenlei_box">
    <!-- 分类 -->
    <div class="nav_box">
      <scroll-view 
        style="height:93vh;width:24%"
        class="menu-wrapper" 
        :scroll-into-view="navId" 
        scroll-with-animation="true"
        scroll-y
      >
        <div :class="navIndex === index ? 'nav_on nav':'nav'" v-for="(item,index) in typeList" :key="index" @click="navClick(index,item)">
          <p class="text">{{item.name}}</p>
        </div>
      </scroll-view>
      <div
        style="height:88vh;width:76%;"
        class="menu-wrapper1" 
      >
        <div class="list">
          <div class="box" v-for="(item,i) in goodsList" :key="i">
            <p class="img">
              <img mode="widthFix" :src="item.img" alt="">
            </p>
            <div class="sp">
              <p class="name">{{item.name}}</p>
              <div class="num">
                <p>销量：{{item.salesVolume}}</p>
                <p>库存：{{item.stockNumber}}</p>
              </div>
              <div class="price_box">
                <p class="price">￥{{item.price}}</p>
                <p class="add">
                  <van-stepper 
                    async-change
                    disable-input
                    v-model="item.value"
                    min="0" 
                    :max="item.stockNumber" 
                    @plus="userChange(item.id,item.value,item.stockNumber,true)"
                    @minus="reduceShopCart(item.id,item.value)"
                  />
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 点购记录浮窗 -->
    <div class="pop_content_box" @click="toJilu" v-if="roomId">
      <p class="img"><img src="/static/images/jilu.png" alt=""></p>
      <p class="text">点购记录</p>
    </div>
    
    <!-- 选好了 -->
    <div class="choiceOk" :style="{ paddingBottom: isPhone?'30px':'0px'}">
      <div class="price_box" @click="changePop">
        <p class="price">￥{{priceMsg.totalPrice?priceMsg.totalPrice:0}}</p>
        <p class="num">已选<span>{{priceMsg.selectedNum?priceMsg.selectedNum:0}}</span>个商品</p>
      </div>
      <p v-if="priceMsg.goodsItemList && priceMsg.goodsItemList.length" class="button" @click="submit">选好了</p>
      <p v-else class="button on">选好了</p>
    </div>

    <!-- 弹窗 -->
    <div class="pop_box">
      <van-popup 
        :show="show" 
        safe-area-inset-bottom
        position="bottom"
        @close="onClose"
        >
          <div class="box">
            <div class="list" :style="{ paddingBottom: isPhone?'140rpx':'150rpx'}">
              <div class="box" v-for="(item,i) in goodsItemList" :key="i">
                <p class="img">
                  <img :src="item.img" alt="">
                </p>
                <div class="sp">
                  <p class="name">{{item.name}}</p>
                  <p class="num">销量：{{item.salesVolume}}</p>
                  <p class="price">￥{{item.price}}</p>
                </div>
                <p class="add">
                  <van-stepper 
                  async-change 
                  disable-input
                  min="0" 
                  :max="item.stockNumber" 
                  v-model="item.selectedNum"
                  @plus="userChange(item.goodsId,item.selectedNum,item.stockNumber,false)" 
                  @minus="reduceShopCart(item.goodsId,item.selectedNum)"  />
                </p>
              </div>
            </div>
          </div>
      </van-popup>
    </div>
  </div>
</template>

<script>
import { Debounce } from "@/utils/index";
import { 
  getGoodsTypeList,
  getGoodsPage,
  selectedGoods,
  getSelectedGoods,
  lockStock,
  getStoreByRoomId
} from "@/api";

import { 
    getToken,
    getusrInfo
} from "@/utils/auth";
export default {
  data() {
    return {
      isPhone:false,// 判断是否苹果手机
      show:false,
      value:1,
      storeId:'',
      typeList:[],
      navIndex:0,
      goodsTypeId:'',
      param:{
        current:1,
        size:10,
      },
      goodsList:[],
      orderId:'',
      priceMsg:{},
      goodsItemList:[],
      roomId:'',
      p_num:0,
      isSaoma:false
    };
  },
  watch:{
goodsList: {
      handler(newVal, oldVal) {
        // ... //监听后的操作
        // debugger
        this.goodsList=newVal
      },
      deep: true, // 加这个属性，深度监听
    },
  },
  methods: {
    toOrder(){
      wx.navigateTo({
        url: '/pages/orderPages/orderConfirm/main',
      });
    },

    changePop(){
      if(this.priceMsg.goodsItemList && this.priceMsg.goodsItemList.length){
        this.show = true
      }
    },

    onClose(){
      this.show = false
    },

    // 增加
    addShopCart(e){
      //console.log(e)
    },

    // 减掉
    reduceShopCart:Debounce(function (id,num) {
      //console.log(num)
      let data = {
        goodsId:id,
        orderId:this.orderId,
        isAdd:1
      }
      selectedGoods(data).then(res=>{
        if(res.statusCode == '00000'){
          this.getUserGoods()
          if(num == 1){
            this.goodsList.map(child=>{
              if(child.id == id){
                child.value = 0
              }
            })
          }
        }else{
          this.$toast('减少失败，请重试')
        }
      })
    },300),

    navClick(index,item){
      //console.log(index,item)
      this.goodsTypeId = item.id
      this.navIndex = index
      this.goodsList = []
      this.param.current = 1
      this.getGoodsList()
    },

    // 获取左边分类
    async getTypeList(){
      this.$showLoading('加载中...')
      await getGoodsTypeList({storeId:this.storeId}).then(res=>{
        if(res.statusCode == '00000'){
          this.goodsTypeId = res.data[0].id
          this.typeList = res.data
          this.getGoodsList()
        }
      })
    },

    // 右边商品列表
    async getGoodsList(){
      const _this = this;
      this.param.goodsTypeId = this.goodsTypeId
      this.param.storeId = this.storeId
      await getGoodsPage(this.param).then(res=>{
        if(res.statusCode == '00000'){
          if(!res.data.shopOpen){
            wx.hideLoading()
            wx.hideNavigationBarLoading();
            wx.stopPullDownRefresh();
            wx.showModal({
              title: '温馨提示',
              content: '亲，配送小弟已下线，辛苦您前往大厅使用智能柜自助购买商品哦~',
              showCancel:false,
              confirmText: '我知道了',
              success: function (res) {
                if (res.confirm) {
                  if(_this.roomId){// 扫码进来
                    wx.reLaunch({
                      url: '/pages/index/main',
                    })
                  }else{
                    wx.navigateBack({
                      delta: 1
                    });
                  }
                }
              }
            })
            return
          }
          if(res.data.iPage.total == '0'){
            return
          }
          this.p_num = this.pagerCount(+res.data.iPage.total,10)
          res.data.iPage.records.map(item=>{
            item.value = 0
            item.price = (item.price/100).toFixed(2)
          })
          this.goodsList = this.goodsList.concat(res.data.iPage.records)
          this.getUserGoods()
          wx.hideLoading()
          wx.hideNavigationBarLoading();
          wx.stopPullDownRefresh();
        }else{
          wx.hideLoading()
          wx.hideNavigationBarLoading();
          wx.stopPullDownRefresh();
        }
      })
    },

    // 用户选择商品
    userChange:Debounce(function (id,num,maxNum,state) {
      //console.log(num+1)
      
      let data = {
        goodsId:id,
        orderId:this.orderId,
        isAdd:0
      }
      selectedGoods(data).then(res=>{
        if(res.statusCode == '00000'){
          if(num+1 == maxNum){
            this.$toast('暂无更多库存~')
          }
          this.getUserGoods()
        }else{
          this.$toast('添加失败，请重试')
        }
      })
    },300),

    // 查询用户选择的商品
    getUserGoods(){
      let data = {
        orderId:this.orderId
      }
      if(this.roomId){// 证明是扫码进来的
        delete data.orderId
        data.roomId = this.roomId
      }else{
        data.orderId = this.orderId
      }
      getSelectedGoods(data).then(res=>{
        if(res.statusCode == '00000'){
          if(res.data.totalPrice){
            res.data.totalPrice = (res.data.totalPrice/100).toFixed(2)
          }
          if(res.data.goodsItemList.length){
            const middleList=[...this.goodsList]
            res.data.goodsItemList.map(item=>{
              item.price = (item.price/100).toFixed(2);
              middleList.map(child=>{
                if(item.goodsId == child.id){
                  child.value = item.selectedNum
                }
              })
            })
            // this.$nextTick(()=>{
            this.goodsList=middleList
            // })
            
          }else{
            this.show = false
          }
          this.goodsItemList = res.data.goodsItemList
          this.priceMsg = res.data
          //console.log(this.goodsItemList)
        }
      })
    },

    // 选好了
    submit:Debounce(function () {
      const _this = this;
      wx.showLoading({
        title: '发起支付...'
      })
      let data = {
        orderId:this.orderId
      }
      if(this.roomId){// 证明是扫码进来的
        delete data.orderId
        data.roomId = this.roomId
      }else{
        data.orderId = this.orderId
      }
      lockStock(data).then(res=>{
        if(res.statusCode == '00000'){
          wx.requestPayment({
            timeStamp:res.data.timeStamp,
            nonceStr:res.data.nonce_str,
            package:`prepay_id=${res.data.prepay_id}`,
            signType:"MD5",
            paySign:res.data.sign,
            success:function(succ){
              if(succ.errMsg === "requestPayment:ok"){
                wx.hideLoading()
                if(_this.roomId){// 证明是扫码进来的
                  wx.navigateTo({
                    url: '/pages/on_order/dd_success/main',
                  });
                }else{
                  wx.navigateBack({
                    delta: 1
                  });
                }
              }
            },
            fail:function(err){
              _this.$toast('取消支付~')
              wx.hideLoading()
            }
          })
        }else{
          _this.getUserGoods()
          _this.getGoodsList()
          wx.hideLoading()
          _this.$toast(res.message)
        }
      })
    },500),

    // 跳转点购记录
    toJilu(){
      wx.navigateTo({
        url: '/pages/on_order/dg_list/main',
      });
    },

    // 计算分页条数
    pagerCount(count ,pageSize){
      if(typeof(count)=="number"){
        if(count>0){
          try {
            var _pagerCount=count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            var c=_pagerCount.toFixed(0);//小数取整
            _pagerCount=c>_pagerCount?c-1:c;//过滤四舍五入
            return _pagerCount;
          } catch (error) {
            return 0;
          }
        }else{
          return 0;
        }
      }else{
        return 0;
      }
    },
  },
  onShow() {
    // 版本更新
    if (wx.canIUse("getUpdateManager")) {
      //console.log("进去版本检测------->");
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
          //下载成功
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: "更新提示",
              content: "新版本已经准备好，是否重启应用？",
              showCancel:false,
              confirmText:'立即重启',
              success: function (res) {
                if (res.confirm) {
                  updateManager.applyUpdate();
                }
              },
            });
          });
          //下载失败
          updateManager.onUpdateFailed(function () {
            wx.showModal({
                title: "已经有新版本了哟~",
                content: "新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~",
            });
          });
        } else {
          //console.log("最新版本-------》");
          this.getUserGoods()
        }
      });
    } else {
      wx.showModal({
        title: "提示",
        content:
        "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。",
      });
    }
  },
  onLoad(options) {
    //console.log(options)
    if(options.scene){// 扫码进来
      this.roomId = options.scene
      this.isSaoma = true
      if(!getToken()){
        wx.login({
          success:(res)=>{
            let code = res.code
            this.$store.dispatch("userLogin", code).then(res=>{
              if(res.statusCode == '00000'){
                getStoreByRoomId({roomId:options.scene}).then(res=>{
                  if(res.statusCode == '00000'){
                    this.storeId = res.data
                    this.getTypeList()
                  }
                })
              }
            })
          }
        })
      }else{
        this.isSaoma = false
        getStoreByRoomId({roomId:options.scene}).then(res=>{
          if(res.statusCode == '00000'){
            this.storeId = res.data
            this.getTypeList()
          }
        })
      }
    }else{
      this.storeId = options.storeId
      this.orderId = options.orderId
      //console.log(this.storeId)
      this.getTypeList()
    }
    //判断手机机型，动态给底部添加样式
    wx.getSystemInfo({
      success: (res) => {
        //console.log("手机信息res" + res.model);
        let modelmes = res.model;
        if (
          modelmes.search("iPhone 13") != -1 ||
          modelmes.search("iPhone 12") != -1 ||
          modelmes.search("iPhone 11") != -1 ||
          modelmes.search("iPhone X") != -1 ||
          modelmes.search("iPhone XR") != -1 ||
          modelmes.search("iPhone XS") != -1
        ) {
          this.isPhone = true
        } else {
          this.isPhone = false
        }
      },
    });
  },
  onReachBottom(){
    //console.log('到底了')
    if(this.p_num == this.param.current){
        this.$toast('小二已经滑到底部啦')
        return
    }
    this.$showLoading('加载中...')
    this.param.current++
    this.getGoodsList()
  },
  onUnload(){
    this.show = false
    this.param.current = 1
    this.goodsList = []
    this.navIndex = 0
    this.roomId = ''
  }
};
</script>

<style lang="scss" scoped>
.fenlei_box{
  .menu-wrapper{
  background: #FAFAFA;
  position: fixed;
  left: 0;
  top:0;
}
  .nav{
  width: 100%;
  height: 154rpx;
  text-align: center;
  color:#333333;
  font-size:30rpx;
  display: flex;
  flex-direction:column;
  align-items: center;
  justify-content: center;
  border-left:4rpx solid transparent;
  font-weight: 500;
  .img{
    width: 60rpx;
    height: 60rpx;
    margin-bottom:17rpx;
    img{
      width: 100%;
      height: 100%;
    }
  }
}
.nav_on{
  background: #FFFFFF;
  border-left:4rpx solid #3E81E9;
}
  .nav_box{
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
  .choiceOk{
    position: fixed;
    bottom:0;
    width: 100%;
    height: 98rpx;
    background: #fff;
    box-shadow: 0px 0px 15rpx 0px rgba(10, 13, 32, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;
    z-index: 9999999;
    .price_box{
      margin-left:56rpx;
      .price{
        color:#333333;
        font-size:40rpx;
      }
      .num{
        color:#999999;
        font-size:24rpx;
        span{
          color:#3E81E9;
        }
      }
    }
    .button{
      width: 206rpx;
      height: 80rpx;
      line-height: 80rpx;
      background: linear-gradient(130.23deg, rgba(9, 166, 254, 1) 0%, rgba(7, 117, 252, 1) 100%);
      color: #FFFFFF;
      font-size: 32rpx;
      text-align: center;
      margin-right: 30rpx;
      border-radius: 10rpx;
      &.on{
        background: #aaa;
      }
    }
  }
  .pop_box{
    /deep/ .van-popup{
      border-top-right-radius: 20rpx;
      border-top-left-radius: 20rpx;
      max-height: 70%;
    }
    .list{
      width: 90%;
      margin:0 auto;
      padding-top:30rpx;
      .title{
        width: 100%;
        height: 86rpx;
        line-height: 86rpx;
        font-size:26rpx;
        color:#999999;
      }
      .box{
        display: flex;
        position: relative;
        margin-bottom:40rpx;
        &:last-child{
          margin-bottom:0;
        }
        .img{
          width: 176rpx;
          height: 176rpx;
          border-radius: 12rpx;
          margin-right:25rpx;
          img{
            width: 100%;
            height: 100%;
          }
        }
        .sp{
          flex: 1;
          .name{
            color:#333333;
            font-size:32rpx;
            margin:10rpx 0 16rpx 0;
          }
          .num{
            color:#999999;
            font-size:26rpx;
            margin-bottom:30rpx;
            display: flex;
            justify-content: space-between;
          }
          .price{
            color:#333333;
            font-size:32rpx;
          }
        }
        .add{
          margin-left:auto;
          /deep/ .van-stepper__minus{
            width: 50rpx !important;
            height: 50rpx !important;
            background: none;
            border:1px solid #3E81E9 !important;
            border-radius:10rpx !important;
            color:#333 !important;
          }
          /deep/ .van-stepper__plus{
            width: 50rpx !important;
            height: 50rpx !important;
            background: #3E81E9;
            color:#fff !important;
            border-radius:10rpx !important;
          }
          /deep/ .van-stepper__input{
            width: 50rpx;
            height: 50rpx;
            background: none;
            font-size:32rpx;
          }
          /deep/ .van-stepper__input--disabled{
            color:#323233 !important;
          }
        }
      }
    }
  }
}
.menu-wrapper1{
  position:relative;
  left: 24%;
  .list{
    width: 90%;
    margin:0 auto;
    padding-bottom:180rpx;
    .title{
      width: 100%;
      height: 86rpx;
      line-height: 86rpx;
      font-size:26rpx;
      color:#999999;
    }
    .box{
      display: flex;
      position: relative;
      margin-bottom:40rpx;
      &:last-child{
        margin-bottom:0;
      }
      .img{
        width: 176rpx;
        height: 176rpx;
        border-radius: 12rpx;
        margin-right:25rpx;
        img{
          width: 100%;
          height: 100%;
        }
      }
      .sp{
        flex: 1;
        .name{
          color:#333333;
          font-size:32rpx;
          margin:10rpx 0 16rpx 0;
        }
        .num{
          color:#999999;
          font-size:26rpx;
          margin-bottom:30rpx;
          display: flex;
          justify-content: space-between;
        }
        .price_box{
          display: flex;
          justify-content: space-between;
          align-items: center;
          .price{
            color:#333333;
            font-size:32rpx;
          }
        }
        
      }
      .add{
        margin-left:auto;
        text-align: center;
        color:#fff;
        font-size:40rpx;
        /deep/ .van-stepper__minus{
          width: 50rpx !important;
          height: 50rpx !important;
          background: none;
          border:1px solid #3E81E9 !important;
          border-radius:10rpx !important;
          color:#333 !important;
        }
        /deep/ .van-stepper__plus{
          width: 50rpx !important;
          height: 50rpx !important;
          background: #3E81E9;
          color:#fff !important;
          border-radius:10rpx !important;
        }
        /deep/ .van-stepper__input{
          width: 50rpx;
          height: 50rpx;
          background: none;
          font-size:32rpx;
        }
        /deep/ .van-stepper__input--disabled{
          color:#323233 !important;
        }
      }
    }
  }
}
.pop_content_box{
  position: fixed;
  right:30rpx;
  top:70%;
  z-index: 10;
  .img{
    width: 80rpx;
    height: 80rpx;
    box-shadow: 0 8rpx 23rpx #c5c4c4;
    border-radius: 50%;
    background: rgb(243, 41, 54);
    font-size:28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin:0 auto;
  }
  img{
    width: 50rpx;
    height: 50rpx;
  }
  .text{
    text-align: center;
    font-size:28rpx;
  }
}
</style>
